package login;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;





import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import platform.AppConfig;
import protocol.ParameterType;
import protocol.ReturnCode;
import io.ClientSession;
import io.OperationResponse;

public class Login91 {
	protected static final Logger log = LoggerFactory.getLogger(Login91.class);
		private static String appid = "116010";  
		private static String appkey = "f4bfbc92dde2814d5f6311113541c640bed30b59d70a3481";
		private static String goUrl ="http://service.sj.91.com/usercenter/ap.aspx?";
	public static void  LoginNo(OperationResponse operationRequest,ClientSession session){
		try {
			 String id = (String)operationRequest.Parameters.get(ParameterType.UserID);
             String pwd = (String)operationRequest.Parameters.get(ParameterType.UserPwd);
             String isGetIP = (String)operationRequest.Parameters.get(ParameterType.IsGetIP);
             String deviceID = (String) operationRequest.Parameters
 					.get(ParameterType.DeviceID);
             String PhoneType=(String) operationRequest.Parameters
     				.get(ParameterType.PhoneType);
         	String[] infor = id.split("[,]", -1);
         	String unid=infor[0];
         	String sessionID=infor[1];
         	int code=checkUserLogin(unid,sessionID);
         	if(code==1){
         		id=unid;
         	}else {
				return;
			}
             if(id.equals("")&&pwd==""){
            	 OperationResponse response = new OperationResponse(
     					operationRequest.OperationCode,
     					AppConfig.dicAppInfo, ReturnCode.GetServer, "");
            	 session.SendOperationResponse(response);
           
             }
             
             operationRequest.Parameters.put(ParameterType.UserID, id);
             OperationResponse responseID = new OperationResponse(
 					operationRequest.OperationCode, operationRequest.Parameters, ReturnCode.HasID,
 					"");
 			session.SendOperationResponse(responseID);
        	 Util.sdkReceived(operationRequest, session, id, deviceID, isGetIP,"jyios",PhoneType,"");
			
		} catch (Exception e) {
			// TODO: handle exception
		log.info("91ios return have a expection ="+e.toString());
		}
		
		
	}
	
	private static int checkUserLogin(String uin,String sessionID) throws Exception{
		String act = "4";
		StringBuilder strSign = new StringBuilder();
		strSign.append(appid);
		strSign.append(act);
		strSign.append(uin);
		strSign.append(sessionID);
		strSign.append(appkey);
		String sign = Util.getMD5Str(strSign.toString());
		StringBuilder getUrl = new StringBuilder();
		getUrl.append("Appid=");
		getUrl.append(appid);
		getUrl.append("&Act=");
		getUrl.append(act);
		getUrl.append("&Uin=");
		getUrl.append(uin);
		getUrl.append("&SessionId=");
		getUrl.append(sessionID);
		getUrl.append("&Sign=");
		getUrl.append(sign);
		return GetResult(HttpGetGo(getUrl.toString()));
	}
	/**
	 * 
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static int GetResult(String jsonStr) throws Exception{
//		Pattern p = Pattern.compile("(?<=\"ErrorCode\":\")\\d{1,3}(?=\")");
//		Matcher m = p.matcher(jsonStr);
//		m.find();{"ErrorCode":"1","ErrorDesc":"鏈夋晥"}
//		return Integer.parseInt(m.group());
		String access_token="";
		if(!jsonStr.equals("")){
		JSONObject token = new JSONObject(jsonStr);
		 access_token = token.optString("ErrorCode");
		
//		//杩欓噷闇�寮曞叆JSON-LIB鍖呭唴鐨凧AR
//		JSONObject jo = JSONObject.fromObject(jsonStr); 
		
		}else {
			log.info("91return have a error result ="+jsonStr);
		}
		return Integer.parseInt(access_token);
	}
	
	
	/**
	 * 鍙戦�GET璇锋眰骞惰幏鍙栫粨鏋�
	 * @param getUrl
	 * @return
	 * @throws Exception
	 */
	public static String HttpGetGo(String getUrl) throws Exception{   
	    StringBuffer readOneLineBuff = new StringBuffer();   
	    String content ="";   
        URL url = new URL( goUrl + getUrl);   
        URLConnection conn = url.openConnection();   
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));          
        String line = "";   
        while ((line = reader.readLine()) != null) {   
            readOneLineBuff.append(line);   
        }   
        content = readOneLineBuff.toString();   
        reader.close();   
	    return content;   
	}   
	public  Runnable getLogin91(OperationResponse operationResponse, ClientSession session){ 
		class Login91ios implements Runnable { 
			private OperationResponse t_operationResponse;
			private ClientSession t_session;
			public Login91ios(OperationResponse operationResponse, ClientSession session)
			{
				t_operationResponse = operationResponse;
				t_session = session;
			}
			
			@Override
			public void run() {
					try {
						LoginNo(t_operationResponse, t_session);
					} catch (Exception e) {
						log.info(Thread.currentThread().getName() + " Login task Error!!!");
					}
				}
        }
	    return new Login91ios(operationResponse, session); 
	 } 
}
